package com.ktjy.ktmall.servlet;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ktjy.ktmall.entity.AjaxResult;
import com.ktjy.ktmall.service.TUserService;
import com.ktjy.ktmall.service.impl.TUserImpl;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.stream.Collectors;

@WebServlet(name = "TUserServlet", urlPatterns = "/uni/user")
public class TUserServlet extends HttpServlet {
    private TUserService userService = null;

    public void init(ServletConfig config) throws ServletException {
        userService = new TUserImpl();
    }

    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        setCorsHeaders(resp);
        resp.setStatus(HttpServletResponse.SC_OK);
    }

    private void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置CORS头
        setCorsHeaders(response);

        // 设置响应内容类型
        response.setContentType("application/json;charset=UTF-8");

        // 使用try-with-resources确保PrintWriter在使用后自动关闭
        try (PrintWriter out = response.getWriter()) {
            // 获取请求参数
            String params = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            System.out.println("Request parameters: " + params); // 打印请求参数

            // 检查请求体是否为空
            if (params == null || params.trim().isEmpty()) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request body is empty or invalid");
                return;
            }

            // 尝试将请求参数字符串转换成JSONObject对象
            JSONObject entries;
            try {
                entries = JSONUtil.parseObj(params);
            } catch (Exception e) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid JSON format: " + e.getMessage());
                return;
            }
            String opr = entries.get("opr", String.class);
            AjaxResult result = new AjaxResult();

            try {
                switch (opr) {
                    case "login":
                        String loginName = entries.getStr("loginName");
                        String password = entries.getStr("password");
                        if (loginName == null || password == null) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'loginName' or 'password' parameter");
                            return;
                        }
                        result = AjaxResult.success("用户登录成功");
                        result.setResult(userService.login(loginName, password));
                        break;
                    case "list":
                        System.out.println("List users request"); // 打印获取用户列表请求
                        result = AjaxResult.success("获取用户列表成功");
                        result.setResult(userService.getAllUsers());
                        break;
                    case "getById":
                        String idParam = entries.getStr("id");
                        if (idParam == null) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'id' parameter");
                            return;
                        }
                        long id = Long.parseLong(idParam);
                        System.out.println("Get user by ID request: id=" + id); // 打印获取用户信息请求
                        result = AjaxResult.success("获取用户信息成功");
                        result.setResult(userService.getUserById(id));
                        break;
                    case "getByLoginName":
                        loginName = entries.getStr("loginName");
                        if (loginName == null) {
                            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing 'loginName' parameter");
                            return;
                        }
                        System.out.println("Get user by login name request: loginName=" + loginName); // 打印获取用户信息请求
                        result = AjaxResult.success("获取用户信息成功");
                        result.setResult(userService.getUserByLoginName(loginName));
                        break;
                    default:
                        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request path");
                        return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                result = AjaxResult.error("获取用户信息失败: " + e.getMessage()); // 打印详细的错误信息
            }

            // 将结果转换为JSON字符串并输出
            String jsonStr = JSONUtil.toJsonStr(result);
            out.println(jsonStr);
            System.out.println(jsonStr); // 用于调试
        }
    }

    private void setCorsHeaders(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        response.setHeader("Access-Control-Allow-Credentials", "true");
    }
}